package com.note.redisLock;

import com.note.redisLock.redLock.KeyConst;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName TaskTest
 * @Description TODO
 * @Author QiBin
 * @Date 2020/6/1010:52
 * @Version 1.0
 **/
@Slf4j
@Service
public class TaskTest {

    /**
     * server.port=3000
     *
     * # redisson lock 单机模式
     * redisson.address=redis://127.0.0.1:6379
     * redisson.password=
     *
     * #哨兵模式
     * #redisson.master-name= master
     * #redisson.password=
     * #redisson.sentinel-addresses=10.47.91.83:26379,10.47.91.83:26380,10.47.91.83:26381
     */
    @Resource
    RedissonClient redissonClient;
    @Test
    public void task(){
        log.info("task start");
        RLock lock = redissonClient.getLock(KeyConst.REDIS_LOCK_KEY);
        boolean getLock = false;

        try {
            if (getLock = lock.tryLock(0,10, TimeUnit.SECONDS)){
                //执行业务逻辑
                System.out.println("拿到锁干活");


            }else {
                log.info("Redisson分布式锁没有获得锁:{},ThreadName:{}",KeyConst.REDIS_LOCK_KEY,Thread.currentThread().getName());
            }

        } catch (InterruptedException e) {
            log.error("Redisson 获取分布式锁异常,异常信息:{}",e);
        }finally {
            if (!getLock){
                return;
            }
            //如果演示的话需要注释该代码;实际应该放开
            lock.unlock();
            log.info("Redisson分布式锁释放锁:{},ThreadName :{}", KeyConst.REDIS_LOCK_KEY, Thread.currentThread().getName());
        }
    }
}
